package com.osig.common.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.common.util.ConfigUtil;
import com.common.util.Tool;
import com.google.common.collect.Lists;
import com.osig.config.Global;
import com.osig.sys.security.SystemAuthorizingRealm.Principal;
import com.osig.sys.security.UsernamePasswordToken;
import com.osig.util.SpringContextHolder;
import com.osig.util.StringUtils;
import com.osig.util.UserUtils;
import com.user.entity.emp.EmpVO;


/**
 * 当成功登录SSO系统时将会返回登录的userid根据此userid建立session会话;
 * 
 * @ClassName: SessionFilter
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author ray@zhou
 * @date 2014-1-23
 *
 */
public class SSO4InvokeContextFilter implements Filter {
	private WebApplicationContext applicationContext;
	private List<String> list;
	private List<String> listpat;
	public SSO4InvokeContextFilter() {
		super();
	}

	/**
	 * 过滤器注销时，触发此方法;
	 */
	public void destroy() {
		// 暂时不做任何处理;
	}
	
	private boolean checkPatten(String url){
		if(url.indexOf(".") > -1){
			String str = url.substring(url.indexOf("."),url.length());
			System.out.println(url);
			//过滤配置的静态资源
			if(list.contains(str)){
				return true;
			}
		}
		for(String urlSuffix : listpat){
			if(urlSuffix.startsWith("/*")){
				urlSuffix = urlSuffix.substring(2, urlSuffix.length());
			}
			if(urlSuffix.endsWith("/*")){
				urlSuffix = urlSuffix.substring(0,urlSuffix.length() - 2);
			}
			if(urlSuffix.indexOf("/*") > -1){
				String[] patens = urlSuffix.split("/*");
				if(url.indexOf(patens[0]) > -1 && url.indexOf(patens[1]) > -1 && url.indexOf(patens[1]) > url.indexOf(patens[0])){
					return true;
				}
			}
			if(url.indexOf(urlSuffix) > -1){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 根据用户id获取用户信息并且把用户信息放入session会话中; @Title: doFilter @Description:
	 * TODO(这里用一句话描述这个方法的作用) @Params @throws
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String uri = request.getRequestURI();
		if(checkPatten(uri)){
			chain.doFilter(request, response);
			return;
		}
		System.out.println(uri);
		//if(url.indexOf(arg0))
		/*Principal principal = UserUtils.getPrincipal();		 		 	    
		if(principal != null&&principal.getEmpV0() != null){
			chain.doFilter(request, response);
			return;
		}
		Cookie cookie = Tool.ReadCookieMap(request).get("token");
		if (cookie == null) {
			response.sendRedirect(ConfigUtil.getValue("sso.web.site"));
			return;
		}	*/
		String code = "H000013";
		Cookie cookie = new Cookie("bbs_0001",String.valueOf(code));
		cookie.setMaxAge(60*60*24*365);
		cookie.setPath("/"); 
		response.addCookie(cookie); 
		
		if (StringUtils.isEmpty(code)) {
			response.sendRedirect(ConfigUtil.getValue("sso.web.site"));
			return;
		}
		EmpVO empVO =new EmpVO();
		empVO.setCode("H000013");
		empVO.setName("徐雄");
		empVO.setDeptCode("000000");
		empVO.setDeptName("品牌市场部");
		empVO.setPostName("品牌市场部");
		UsernamePasswordToken token = new UsernamePasswordToken(empVO);
		token.setEmpV0(empVO);
		token.setUsername(empVO.getCode());
		token.setPassword("".toCharArray());
		token.setRememberMe(false);
		token.setCookie(cookie);
		Subject subject = SecurityUtils.getSubject();
		subject.login(token);
		chain.doFilter(request, response);
	}

	/**
	 * 初始化Spring上下文;
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		WebApplicationContext applicationContext = WebApplicationContextUtils
				.getWebApplicationContext(filterConfig.getServletContext());
		this.applicationContext = applicationContext;
		this.list = Lists.newArrayList();
		this.listpat = Lists.newArrayList();
		for(String str : Global.getConfig("url.anon").split(" ")){
			if(str.indexOf(".") > -1){
				list.add(str);
			}else{
				listpat.add(str);
			}
		}
	}
}
